package br.uniriotec.pssgbd.unterhaltung.view.controle;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.uniriotec.pssgbd.unterhaltung.model.bo.RotuloBO;
import br.uniriotec.pssgbd.unterhaltung.model.bo.UsuarioBO;
import br.uniriotec.pssgbd.unterhaltung.model.entidade.Usuario;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @throws Exception 
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet(){
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		Usuario user = null;
		
		try {
			user = UsuarioBO.getInstance().recuperarUsuario(username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		if(user != null)
		{
			if((username.equals(user.getLogin()) && password.equals(user.getSenha())))
			{
				HttpSession session = request.getSession();
				session.setAttribute("username",username);
						
				RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
				rd.forward(request,response);
			}
			else
			{
				response.sendRedirect("login.jsp");
			}
		}
		else
		{
			response.sendRedirect("login.jsp");
		}
	}

}
